"""
base模板中加入未激活提示
未认证用户在个人中心点击‘去激活’按钮
视图1——发送邮件到用户邮箱，邮件里包含了一个url指向视图2，url中包含了用户的信息
视图2——在数据库中修改用户的认证状态
"""
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app

from apps import mail


# def generate_verify_email_url(user):
#     """
#     生成邮箱验证链接
#     :param user: 当前登录用户
#     :return: 验证邮件中的URL
#     """
#     serializer = Serializer(current_app.config['SECRET_KEY'], expires_in=3600)
#     data = {'username': user.username, 'email': user.email}
#     token = serializer.dumps(data).decode()
#     verify_url = current_app.config['EMAIL_VERIFY_URL'] + '?token=' + token
#     return verify_url


def send_mail(message):
    """发送邮件辅助函数"""
    try:
        mail.send(message)
    except Exception as e1:
        print('****************************')
        current_app.logger.info(e1)
        print('****************************')
        # 记录默认配置
        default_username = current_app.config['MAIL_USERNAME']
        default_password = current_app.config['MAIL_PASSWORD']
        default_mail_server = current_app.config['MAIL_SERVER']
        for config in current_app.config['EXTRA_MAIL_CONFIGS']:
            # 修改配置，使用备用邮箱
            current_app.config['MAIL_USERNAME'] = config['MAIL_USERNAME']
            current_app.config['MAIL_PASSWORD'] = config['MAIL_PASSWORD']
            current_app.config['MAIL_SERVER'] = config['MAIL_SERVER']
            try:
                mail.send(message)
                # 还原配置
                current_app.config['MAIL_USERNAME'] = default_username
                current_app.config['MAIL_PASSWORD'] = default_password
                current_app.config['MAIL_SERVER'] = default_mail_server
                break
            except Exception as e2:
                print('****************************')
                current_app.logger.info(e2)
                print('****************************')
        else:
            # 还原配置
            current_app.config['MAIL_USERNAME'] = default_username
            current_app.config['MAIL_PASSWORD'] = default_password
            current_app.config['MAIL_SERVER'] = default_mail_server
            raise Exception('邮件发送失败')
